<template>
  <view class="container">
    <uni-forms :modelValue="state" :rules="formRules">
      <uni-forms-item label="附件" name="file">
        <uni-file-picker v-model="tempFile" limit="1" file-extname="docx,pptx" :auto-upload="false" file-mediatype="all"
          @select="selectFile">
          <button size="mini" type="primary" class="mini-btn">上传文件</button>
        </uni-file-picker>
      </uni-forms-item>
      <uni-forms-item label="知识点" name="knowledgepoint">
        <uni-data-picker v-model="state.knowledgepoint" :localdata="subjectKnowledgeList" popup-title="请选择"
          @change="onSubjectChange" @nodeclick="onKnowledgeclick"></uni-data-picker>
      </uni-forms-item>
      <uni-forms-item label="类型" name="type">
        <uni-data-checkbox v-model="state.type" :localdata="fileTypeOption"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item label="课型" name="type">
        <uni-data-checkbox v-model="state.paper_type" :localdata="paperTypeOption"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item label="标题" name="title">
        <uni-easyinput type="text" v-model="state.title" placeholder="请输入标题" />
      </uni-forms-item>
      <uni-forms-item label="说明" name="remark">
        <uni-easyinput type="textarea" v-model="state.remark" placeholder="请输入说明" />
      </uni-forms-item>
      <view class="uni-btn-v twoButton">
        <button form-type="submit" type="primary" size="mini" @click="formSubmit">提交</button>
      </view>
    </uni-forms>
  </view>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
import UniDataPicker from '@dcloudio/uni-ui/lib/uni-data-picker/uni-data-picker.vue'
import UniForms from '@dcloudio/uni-ui/lib/uni-forms/uni-forms.vue'
import UniFilePicker from '@dcloudio/uni-ui/lib/uni-file-picker/uni-file-picker.vue'
import UniDataCheckbox from '@dcloudio/uni-ui/lib/uni-data-checkbox/uni-data-checkbox.vue'
import { getSubjectKnowledgeAPI, postGuidePaperFileAPI } from '@/services/home'
import { onLoad } from '@dcloudio/uni-app'
import { uploadCommonFile } from '@/utils/http'

const maxLengthRemark = 200
const maxLenghthTitle = 20
type subjectKnowledgeItem = {
  value: string
  name: string
  childrenL: any[]
}
const subjectKnowledgeList = ref<subjectKnowledgeItem[]>([])
// 通用性变量
const state = reactive({
  title: '',
  remark: '',
  type: 0,
  paper_type: 2,
  knowledgepoint: -1,
  file: [],
  open_level: 'public',
  bank_point: 5,
})
const tempFile = ref<any[]>([])
// 选择框类型
type checkItem = {
  value: number
  text: string
  disable?: boolean
}
// 课型选择项
const paperTypeOption: checkItem[] = [
  { value: 1, text: '新课', disable: false },
  { value: 2, text: '复习课', disable: false },
]
// 文件类型选择项
const fileTypeOption: checkItem[] = [
  { value: 1, text: '导学案', disable: true },
  { value: 2, text: '课件', disable: true },
]
// 学科变了
const onSubjectChange = (e: any) => {
  console.log('学科改了', e)
}
// 选择了知识点
const onKnowledgeclick = (e: any) => {
  console.log('选择了节点')
  if (e.parent_value !== undefined) {
    state.knowledgepoint = e.value
  }
}
// 提交导学案
const formSubmit = async (e: any) => {
  console.log('要提交导学案拉')
  await Promise.all([uploadPaperFile()])
}
const postPaperFileData = async () => {
  const res = await postGuidePaperFileAPI(state)
  console.log('提交导学案结果：', res)
  if (res.code === 200 || res.code === 201) {
    uni.showToast({ icon: 'success', title: '提交成功' })
  } else if (res.code === 1099) {
    uni.showToast({ icon: 'error', title: '提交失败' })
  } else {
    uni.showToast({ icon: 'error', title: '提交错误' })
  }
}
// 根据文件拓展名，判断文件类型
const judgeTypeByFile = (suffix: string) => {
  if (suffix == 'docx') {
    state.type = 1
  } else {
    if (suffix == 'pptx') {
      state.type = 2
    }
  }
  console.log('suffix', suffix)
  console.log('state.type', state.type)
}
// 选择了正确格式的文件
const selectFile = (e: any) => {
  if (e.tempFilePaths.length > 0) {
    state.file = e.tempFilePaths[0]
  }
  judgeTypeByFile(e.tempFilePaths[0].slice(-4))
}

// 选择了文件, 成功后再提交表单
const uploadPaperFile = async () => {
  let formData = {}
  console.log('要给服务器提交文件啦')
  const res = await uploadCommonFile(
    '/UploadGuidePaperFileServer/',
    state.file,
    'upload_file',
    formData,
  )
  console.log('上传文件结果：', res)
  if (res.code == 200) {
    state.file = res.data.results
    postPaperFileData()
  } else {
    uni.showToast({ icon: 'error', title: 'upload file fail!' })
  }
}
// 请求所有学科的知识点，结果是二级嵌套数组
const getSubjectKnowledgeData = async () => {
  console.log('要获取学科知识点拉')
  const res = await getSubjectKnowledgeAPI()
  if (res.code == 200) {
    subjectKnowledgeList.value = res.data.results
    console.log('获取所有学科知识点：', subjectKnowledgeList.value)
  } else {
    uni.showToast({ icon: 'error', title: '获取失败' })
  }
}
// 页面加载
onLoad(async () => {
  console.log('页面加载')
  await Promise.all([getSubjectKnowledgeData()])
})
const formRules = {
  // 对title字段进行必填验证
  title: {
    rules: [
      {
        required: true,
        errorMessage: '请输入标题',
      },
      {
        minLength: 5,
        maxLength: 20,
        errorMessage: '标题长度在 {minLength} 到 {maxLength} 个字符',
      },
    ],
  },
  // remarks字段进行必填验证
  remarks: {
    rules: [
      {
        required: true,
        errorMessage: '请输入介绍',
      },
      {
        minLength: 10,
        maxLength: 200,
        errorMessage: '介绍长度在 {minLength} 到 {maxLength} 个字符',
      },
    ],
  },
  // type字段进行必填验证
  type: {
    rules: [
      {
        required: true,
        errorMessage: '请选择类型',
      },
      {
        minimum: 1,
        maximum: 2,
        errorMessage: '请选择类型',
      },
    ],
  },
  // knowledgepoint字段进行必填验证
  knowledgepoint: {
    rules: [
      {
        required: true,
        errorMessage: '请选择知识点',
      },
      {
        minimum: 1,
        errorMessage: '请选择知识点',
      },
    ],
  },
}
</script>
<style lang="scss" scoped>
.container {
  font-size: 30rpx;
  margin: 22rpx;
  padding: 5rpx;
}

.uni-input {
  border: 1rpx solid gray;
  border-radius: 20rpx;
}

.uni-form-item .title {
  padding: 10rpx 0;
}

.title {
  font-size: 30rpx;
  font-weight: bold;
  margin: 10rpx 0 5rpx 0;
}

.data-pickerview {
  height: 400px;
  border: 1px #e5e5e5 solid;
}

.popper__arrow {
  top: -6px;
  left: 50%;
  margin-right: 3px;
  border-top-width: 0;
  border-bottom-color: #ebeef5;
}

.popper__arrow {
  top: -6px;
  left: 50%;
  margin-right: 3px;
  border-top-width: 0;
  border-bottom-color: #ebeef5;
}

.twoButton {
  padding: 10rpx;
  display: flex;
  flex-flow: row nowrap;
  justify-content: center;
}
</style>
